package com.chenhs.oop.study.多线程;

/**
 * @program: JAVA300
 * @description: 锁
 * @author: peanut
 * @create: 2019-07-21 16:57
 */
public class Demo6 implements Runnable {
    /*要买多少票*/
    Integer ticketUmnber;
    /*买票人*/
    String name;
    Ciname ciname;
    boolean b = true;

    private Demo6(Ciname ciname, String name, Integer ticket) {
        this.name = name;
        this.ticketUmnber = ticket;
        this.ciname = ciname;
    }

    @Override
    public void run() {
        synchronized (ciname) {
            while (b) {
                b = ciname.test(name, ticketUmnber);
                Thread.yield();
            }
        }

    }
    static class Ciname {
        int SUM_TICKET;
        public Ciname(int ticket) {
            this.SUM_TICKET = ticket;
        }
        /*出的动作*/
        public boolean test(String name, Integer take) {
            System.out.println(Thread.currentThread().getName());
            if (take > SUM_TICKET) {
                System.out.println("余票不足，余票为：" + SUM_TICKET + "张，购票失败。");
                return false;
            }
            SUM_TICKET = SUM_TICKET - take;
            System.out.println(name + ",你好，你已购票" + take + "张，" + "当前影院剩余票数为：" + SUM_TICKET + "张。");
            return true;
        }

    }
    public static void main(String[] args) {
        /*创建影院实例*/
        Ciname ciname = new Ciname(500);
        /*开起线程*/
        new Thread(new Demo6(ciname, "小华", 6), "小华").start();
        new Thread(new Demo6(ciname, "小红", 5), "小红").start();

    }
}
